package com.jumi.microservice.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

/**
 * 暂时不使用FastJson处理序列化
 * @author Administrator
 */
public class FastJsonConfiguration implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(FastJsonConfiguration.class);

    final static String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 使用阿里 fastjson 作为 JSON MessageConverter
     *
     * @param converters 转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig ();
        config.setSerializerFeatures(
                // 将 String 类型的 null 转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将 Number 类型的 null 转成 0
                //SerializerFeature.WriteNullNumberAsZero,
                // 将 List 类型的 null 转成 []
                //SerializerFeature.WriteNullListAsEmpty,
                // 将 Boolean 类型的 null 转成 false
                //SerializerFeature.WriteNullBooleanAsFalse,

                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);

        converter.setFastJsonConfig(config);

        ValueFilter dateFilter = (Object var1, String var2, Object var3) -> {
            try {
                if (var3 == null && var1 != null && Date.class.isAssignableFrom(var1.getClass().getDeclaredField(var2).getType())) {
                    return "";
                }

                if (var3 == null && var1 != null && LocalDateTime.class.isAssignableFrom(var1.getClass().getDeclaredField(var2).getType())) {
                    return "";
                }

            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            return var3;
        };
        config.setSerializeFilters(dateFilter);
        config.setDateFormat(DATE_FORMAT);

        converter.setDefaultCharset(StandardCharsets.UTF_8);
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题，相当于在 Controller 上的 @RequestMapping 中加了个属性 produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}